"use strict";
// 在其他文件中导入 rollTaskList 函数
const { rollTask } = require('./dispatchBuild');
/**
 * @name build
 * 建筑
 */
/**
* @name buildLevel
* @param int id 建筑id
* @param int lv 建筑目标等级
* 通用建筑升级
*/
exports.buildLevel = async function () {
    let id = this.get('id', 'int');
    let lv = this.get('lv', 'int');
    //读表拿出升级条件
    let buildConfig = this.config('build', id);
    if (!buildConfig) {
        return this.quick_error("M2saghge50", "配置不存在", id);
    }
    //拿到升级组id 
    let upConfig = this.config('lvgroupBuild', buildConfig.upgradeGroup);
    if (!upConfig) {
        return this.quick_error("M2saghge50", "配置不存在", buildConfig.upgradeGroup);
    }
    this.updater.role.key('buildingsInfo.' + id);
    this.updater.role.key('incubateList');
    let upData = {};
    for (let k in upConfig.Coll) {
        if (upConfig.Coll[k].buildLevel == lv) {
            upData = upConfig.Coll[k];
            break;
        }
    }
    if (upData == {}) {
        return this.quick_error("M2saghge50", "等级达到最大值");
    }
    for (let k in upData.conditionList) {
        let key = upData.conditionList[k].condition;
        if (key == '') {
            continue;
        }
        this.updater.record.key(upData.conditionList[k].condition);
    }
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + id) || { "level": 0 };
    //等级验证
    if (buildData.level + 1 != lv) {
        return this.quick_error("M2saghge50", "等级错误");
    }
    //根据表里的条件，判断是否能升级
    for (let k in upData.conditionList) {
        let key = upData.conditionList[k].condition;
        let val = upData.conditionList[k].value;
        if (key == '') {
            continue;
        }
        let conVal = this.updater.record.get(key) || 0;
        if (conVal < val) {
            return this.quick_error("M2saghge50", "条件不足");
        }
    }
    //在这里测试一下sub 物品组的情况
    //计算消耗的资源数量
    if (upData.upgradeCost != 0) {
        this.updater.sub(upData.upgradeCost, 1);
    }

    buildData.level++;
    //判断下是不是核心建筑
    let mainBuildId = this.config("base", "basicBuildId").val;
    if (mainBuildId == id) {
        this.updater.record.max(61, buildData.level);
    }

    //特殊判断1：资源建筑升级至1级 添加 beginTime
    let recourceBuildConfig = this.config('collectionBuild', id);
    if (recourceBuildConfig && lv == 1) {
        buildData["beginTime"] = Date.now();
    }
    //特殊判断2: 等级同步器建筑升级，增加槽位
    let syncBuildId = this.config('base', 'collectBuild_LevelConnect').val;
    if (!syncBuildId) {
        return this.quick_error('等级同步器未配置');
    }
    if (syncBuildId == id && lv >= 1 && lv <= 5) {
        let slotIdConfig = this.config('lvConnectBuild', lv);
        if (!slotIdConfig) {
            return this.quick_error('M2saghge50', '槽位ID配置不存在')
        }
        if (buildData.slot == undefined) {
            buildData["slot"] = {};
        }
        buildData.slot[slotIdConfig.slotId] = {};
    }
    //特殊判断3：升级白白兵营 (扩容孵蛋器槽位，升级蛋池)
    let incubatorEggBuildId = this.config('base', 'collectBuild_PlayerBagBigger').val;
    if (id == incubatorEggBuildId) {
        let incubateList = this.updater.role.get('incubateList');
        let config = this.config('Incubator');
        if (!config) {
            return this.quick_error('M2saghge40', '孵化器配置不存在');
        }
        for (let item in config) {
            if (lv >= config[item].unlockBuildLevel && !incubateList[item]) {
                incubateList[item] = { "eggID": '', "beginTime": '' };
            }
        }
        this.updater.role.set('incubateList', incubateList);
    }

    //派遣建筑初始化
    const BUILDID = this.config('base', 'collectBuild_OrdersDistribute').val;
    if (id == BUILDID && lv == 1) {
        let taskData = rollTask(buildData.level);
        buildData.taskList = taskData;
    }

    this.updater.role.set('buildingsInfo.' + id, buildData);
    return this.updater.save();
}

/**
* @name setBuildMap
* @param string siteID 位置ID
* @param string buildID 建筑唯一ID
* 在地图保存建筑坐标
*/
exports.setBuildMap = async function () {
    let siteID = this.get('siteID', 'string');
    let buildID = this.get('buildID', 'string');
    this.updater.role.key('buildmap');
    if (buildID != '') {
        this.updater.item.key(buildID);
    }
    await this.updater.data();
    let buildingsData = this.updater.role.get('buildmap') || {};
    if (buildID != '') {
        let buildData = this.updater.item.get(buildID);
        if (!buildData) {
            return this.quick_error("M2saghge50", "建筑不存在", buildID);
        }
        //主建筑不能移动
        let mainBuildId = this.config("base", "basicBuildId").val;
        if (mainBuildId == buildData.id) {
            return this.quick_error("M2saghge50", "主建筑不能移动");
        }
        // //判断是否已经使用过建筑了
        for (let key in buildingsData) {
            if (buildingsData[key] == buildID) {
                return this.quick_error("M2saghge50", "该建筑已经被使用了");
            }
        }
        buildingsData[siteID] = buildID;
    } else {
        delete buildingsData[siteID];
    }
    this.updater.role.set('buildmap', buildingsData);
    return this.updater.save();
}
//resourceBuild 资源建筑
//收菜接口
//unitRoom 兵营 暂时不用写了
//syncBuild 同步器
//设置对应的崽崽

//dispatchBuild 派遣建筑

/**
 * @name getResourceBuild
 * @param string buildStr 资源建筑id字符串, 用 , 分隔
 * 获取资源建筑收益
 */
exports.getResourceBuild = async function () {
    let buildList = this.get('buildStr', 'string').split(',');
    if (buildList.length < 1) {
        return this.quick_error('M2saghge140', '参数错误');
    }

    let basicBuildId = this.config('base', 'basicBuildId').val;
    if (!basicBuildId) {
        return this.quick_error('主基地ID配置不存在');
    }
    this.updater.role.key('buildingsInfo');
    await this.updater.data();
    let buildingsInfo = this.updater.role.get('buildingsInfo');

    //准备工作 表配置：主基地对应等级的收益上限
    if (buildingsInfo[basicBuildId].level == 0) {
        return this.quick_error('主基地等级为0级无收益，先升级主基地等级');
    }
    let baseBuildLevelConfig = this.config('baseBuild', buildingsInfo[basicBuildId].level).getitem;
    if (!baseBuildLevelConfig) {
        return this.quick_error('主基地等级限制收益上限配置不存在', buildingsInfo[basicBuildId].level);
    }

    //遍历需要收益的建筑
    buildList.forEach(buildId => {
        if (buildingsInfo[buildId] == 0) {
            return this.quick_error('该建筑等级为0级无收益，先升级建筑');
        }
        let buildData = buildingsInfo[buildId];
        let collectItem = '';
        let addTime = 0;
        let collectNum = 0;
        let timeRemaining = 0;

        if (buildData.hasOwnProperty('addTime')) {
            addTime = buildData.addTime;
        }
        let collectionBuildConfig = this.config('collectionBuild', buildId);
        if (!collectionBuildConfig) {
            return this.quick_error('资源建筑收益配置不存在', buildId);
        }
        //遍历至对应的收益组，计算收益，确定collectItem 收益物品ID
        for (let item of collectionBuildConfig.Coll) {
            //找到符合该建筑等级的收益组
            if (item.buildLevel == buildData.level && buildData.hasOwnProperty('beginTime')) {
                collectNum = (Math.floor((Date.now() - buildData['beginTime'] + addTime) / (item.collectTime * 1000))) * item.collectNum;
                timeRemaining = (Date.now() - buildData['beginTime'] + addTime) % (item.collectTime * 1000);
                collectItem = item.collectItem;
                this.updater.role.set('buildingsInfo.' + buildId, { "level": buildData.level, "beginTime": Date.now(), "addTime": timeRemaining });
                break;
            }
        }
        //判断是否超过主基地等级的收益上限, 确定collectNum收益数量
        for (let getItem of baseBuildLevelConfig) {
            if (getItem.buildId == buildId) {
                collectNum = collectNum > getItem.maxNumber ? getItem.maxNumber : collectNum;
                break;
            }
        }
        this.updater.add(collectItem, collectNum);
    });
    return this.updater.save();
}

/**
 * @name setSyncBuild
 * @param int slotId 同步器槽位Id
 * @param string idString 放置于同步器中的俩unit唯一ID，用，分隔
 * 设置同步器建筑
 */
exports.setSyncBuild = async function () {
    let slotId = this.get('slotId', 'int');
    let unitIdList = this.get('idString', 'stirng').split(',');
    if (!slotId) {
        return this.quick_error('M2saghge140', '槽位ID参数错误');
    }
    if (unitIdList.length != 2) {
        return this.quick_error('M2saghge140', 'unit个数错误，必须提供两个unit');
    }
    let providerId = unitIdList[0];
    let beneficiaryId = unitIdList[1];

    //获取role的同步器建筑数据
    let syncBuildId = this.config('base', 'collectBuild_LevelConnect').val;
    if (!syncBuildId) {
        return this.quick_error('同步器建筑未配置');
    }

    this.updater.role.key('syncedUnit');
    this.updater.role.key('buildingsInfo.' + syncBuildId);
    this.updater.item.key(providerId);
    this.updater.item.key(beneficiaryId);
    await this.updater.data();
    let syncedUnit = this.updater.role.get('syncedUnit');
    let buildInfo = this.updater.role.get('buildingsInfo.' + syncBuildId) || { "level": 0, "slot": {} };
    let providerData = this.updater.item.get(providerId);
    let beneficiaryData = this.updater.item.get(beneficiaryId);

    if (!providerData || !beneficiaryData) {
        return this.quick_error('未拥有unit');
    }
    //判断槽位是否存在
    if (buildInfo.slot[slotId] == undefined) {
        return this.quick_error('同步器建筑该槽位未解锁，先升级同步器或购买槽位');
    }
    //判断提供者的lv > 受益者 ？
    if (providerData.lv <= beneficiaryData.lv) {
        return this.quick_error('提供者的等级不大于受益者');
    }

    //开始同步等级
    //存储被同步unit的等级信息
    syncedUnit[beneficiaryId] = { "lv": beneficiaryData.lv, "skillList": beneficiaryData.skillList };
    //更改beneficiaryUnit 的等级数据
    let lvArr = [];
    for (let skillId in providerData.skillList) {
        lvArr.push(providerData.skillList[skillId]);
    }
    let i = 0;
    for (let skill in beneficiaryData.skillList) {
        beneficiaryData.skillList[skill] = lvArr[i++];
    }
    //存储数据到buildingsInfo
    buildInfo.slot[slotId].providerId = providerId;
    buildInfo.slot[slotId].beneficiaryId = beneficiaryId;

    this.updater.role.set('buildingsInfo.' + syncBuildId, buildInfo);
    this.updater.role.set('syncedUnit', syncedUnit);
    this.updater.item.set(beneficiaryId, 'lv', providerData.lv);
    this.updater.item.set(beneficiaryId, 'skillList', beneficiaryData.skillList);

    return this.updater.save();
}

/**
 * @name buySyncBuildSlot
 * @param int slotId 需要购买的槽位ID
 * 购买同步器的槽位
 */
exports.buySyncBuildSlot = async function () {
    let slotId = this.get('slotId', 'int');
    if (!slotId) {
        return this.quick_error('M2saghge140', '参数错误', slotId);
    }
    if (slotId >= 1 && slotId <= 5) {
        return this.quick_error('该槽位不可购买，需通过升级同步器建筑获取', slotId);
    }

    //同步器槽位配置
    let config = this.config('lvConnectBuild', slotId);
    if (!config) {
        return this.quick_error('配置不存在', slotId);
    }
    //同步器id配置
    let syncBuildId = this.config('base', 'collectBuild_LevelConnect').val;
    if (!syncBuildId) {
        return this.quick_error('同步器建筑未配置');
    }
    this.updater.role.key('buildingsInfo.' + syncBuildId);
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + syncBuildId) || { "level": 0, "slot": {} };

    //购买
    //添加槽位6
    buildData.slot[slotId] = {};
    //扣道具
    this.updater.item.sub(config.itemID, config.Num);
    this.updater.role.set('buildingsInfo.' + syncBuildId, buildData);

    return this.updater.save();
}

/**
 * @name relieveSyncBuild
 * @param int slotId 解除同步器的槽位Id
 * 解除同步器
 */
exports.relieveSyncBuild = async function () {
    let slotId = this.get('slotId', 'int');
    if (!slotId) {
        return this.quick_error('M2saghge140', '参数错误', slotId);
    }

    let syncBuildId = this.config('base', 'collectBuild_LevelConnect').val;
    if (!syncBuildId) {
        return this.quick_error('同步器建筑未配置');
    }
    this.updater.role.key('buildingsInfo.' + syncBuildId);
    this.updater.role.key('syncedUnit');
    await this.updater.data();
    let buildData = this.updater.role.get('buildingsInfo.' + syncBuildId) || { "level": 0, "slot": {} }

    if (buildData.slot[slotId] == {}) {
        return this.quick_error('该槽位上没有同步的unit')
    }
    //收益的unit原等级数据
    let beneficiaryId = buildData.slot[slotId].beneficiaryId;

    let syncedUnit = this.updater.role.get('syncedUnit');
    let beneficiaryData = syncedUnit[beneficiaryId];
    delete syncedUnit[beneficiaryId];

    //设置槽位为{}
    buildData.slot[slotId] = {};

    this.updater.role.set('buildingsInfo.' + syncBuildId, buildData);
    this.updater.role.set('syncedUnit', syncedUnit);
    this.updater.item.set(beneficiaryId, 'lv', beneficiaryData.lv);
    this.updater.item.set(beneficiaryId, 'skillList', beneficiaryData.skillList);

    return this.updater.save();
}



